#include <algorithm>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>

typedef std::vector< std::pair<int, std::vector<unsigned int> > > Matrix;

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

int str2int(std::string str) {
    return atoi(str.c_str());
}

int main() {
    std::vector<std::string> strs;
    std::vector<std::string> gene_ids_str;
    std::vector<unsigned int> gene_ids;
    std::string input_line;
    Matrix matrix;
    Matrix::iterator it1;
    Matrix::iterator it2;
    int set_length;
    
    // инициализация векторов
    time_t start_time = time(0);
    while(getline(std::cin, input_line)) {
        std::vector<std::string> strs = split(input_line, '\t');
        gene_ids_str = split(strs[1], ',');
        gene_ids.resize(gene_ids_str.size());
        std::transform(gene_ids_str.begin(), gene_ids_str.end(), gene_ids.begin(), str2int);
        std::sort(gene_ids.begin(), gene_ids.end());
        matrix.push_back( std::make_pair(str2int(strs[0]), gene_ids) );
    };    
    std::cerr << "Got " << matrix.size() << " vectors in " << time(0) - start_time << " seconds" << std::endl;    
    start_time = time(0);
    
    int LIMIT_LOOP_COUNTER = 0;
    for (it1=matrix.begin(); it1<matrix.end(); it1++) {
        // Temporary limit
        //LIMIT_LOOP_COUNTER ++;
        //if (LIMIT_LOOP_COUNTER > 20) break;
        // end limit
        for (it2=matrix.begin(); it2<matrix.end(); it2++) {
            if ((*it1).first < (*it2).first) {
                std::vector<unsigned int> gene_ids_set;
                std::insert_iterator<std::vector<unsigned int> > gene_ids_set_ins(gene_ids_set, gene_ids_set.begin());
                std::set_intersection((*it1).second.begin(), (*it1).second.end(), (*it2).second.begin(), (*it2).second.end(), gene_ids_set_ins);
                set_length = gene_ids_set.size();
                if (set_length > 0) {
                    std::cout << (*it1).first << "," << (*it2).first << "\t" \
                        << (*it1).second.size() << "," << (*it2).second.size() \
                        << "," << set_length << std::endl;
                }
            }
        }
    }

    std::cerr << "Processed in " << time(0) - start_time << " seconds" << std::endl;
    
    return 0;
}
